﻿using System;
using GAIQ;

namespace DCIMAP.GANS.GeneticAlgorithms.Legacy
{
    
    [Serializable]
    public class StringArrayGene : ArrayGene
    {
        
        private readonly string[] code;

        
        public StringArrayGene(int length)
        {
            code = new string[length];
        }

        
        public string[] StringCode
        {
            get { return code; }
        }

        public int getLength() {
            return code.Length;
        }

        /// <inheritdoc/>
        public override Array Code
        {
            get { return code; }
        }

        /// <inheritdoc/>
        /// 
        public string prettyPrint()
        {
            return helpPrettyPrint(StringCode.Length - 1);
        }
        private string helpPrettyPrint(int root)
        {
            if (isLeaf(root))
            {
                return StringCode[root];
            }
            else
            {
                string rightTree = helpPrettyPrint(root - 1);
                int leftRoot = getSubtree(root - 1)[0] - 1;
                string leftTree = helpPrettyPrint(leftRoot);
                return "(" + leftTree + StringCode[root] + rightTree + ")";
            }
        }
        /// <summary> Returns left and right border of subtree with node Node </summary>
        public int[] getSubtree(int Node)
        {
            int[] result = new int[2];
            if (isLeaf(Node))
            {
                result[0] = Node;
                result[1] = Node;
            }
            else
            {
                int[] leftSubtree = getSubtree(Node - 1);
                int[] rightSubtree = getSubtree(leftSubtree[0] - 1);
                result[0] = rightSubtree[0];
                result[1] = Node;
            }
            return result;

        }
        public bool isLeaf(int Node)
        {
            return !ListOp.isOp(StringCode[Node]);
        }
        public override bool AreIdentical(Gene _g)
        {
            StringArrayGene g = (StringArrayGene)_g;
            if (g.Code.Length != Code.Length)
                return false;
            return base.AreIdentical(_g);
        }
        public override Gene CreateEmpty()
        {
            return new StringArrayGene(code.Length);
        }
    }
}